import {Injectable} from "@angular/core";
import {SqliteService} from "./sqlite.service";
import {AppService} from "./app.service";
import {ResDataModel} from "../models/res-data-model";

@Injectable()
export class OrgService{
  constructor(private sqliteService: SqliteService,
              private appService: AppService){

  }

  /**
   * 在SQLite中创建机构表
   */
  createOrgTable(){
    var sql = `CREATE TABLE
                IF NOT EXISTS app_sys_org
                    (
                      cId         VARCHAR2(32) PRIMARY KEY,
                      jgmc         VARCHAR2(300) NOT NULL,
                      jgjc         VARCHAR2(150),
                      jgbz         VARCHAR2(1) NOT NULL,
                      sjjgDm      VARCHAR2(32),
                      sjjgMc       VARCHAR2(300),
                      jgdz         VARCHAR2(300),
                      xzqhDm      VARCHAR2(6),
                      yxbz         VARCHAR2(1) not null
                    );`;
    this.sqliteService.execSql(sql,[]).then(data=>{
      console.log(data)
    }).catch(err =>{
      console.error(err);
    })
  }

  /**
   * 同步机构数据
   */
  sysnOrg(callback?){
//先删除原来的数据
    this.sqliteService.execSql('delete from app_sys_org',[]);
    //从服务器获取数据

    this.appService.httpPost('AppOrgCtrl_list',{},null,(res:ResDataModel)=>{
      let list:any[] = res.datas[0].trs;
      list.forEach(value=>{
        var cId = value.tds.cId.value;
        var jgmc = value.tds.jgmc.value;
        var jgjc = value.tds.jgmc.value;
        var jgbz = value.tds.jgbz.value;
        var sjjgDm = value.tds.sjjgDm.value;
        var sjjgMc = value.tds.sjjgmc.value;
        var jgdz = value.tds.jgdz.value;
        var xzqhDm = value.tds.xzqhDm.value;
        var yxbz = value.tds.yxbz.value;
        var sql = "Insert into app_sys_org values (?,?,?,?,?,?,?,?,?)";
        var param:Array<string> = [cId,jgmc,jgjc,jgbz,sjjgDm,sjjgMc,jgdz,xzqhDm,yxbz];
        this.sqliteService.execSql(sql,param);
      })
      //执行回调
      if(callback){
        callback();
      }
    },false)
  }
}
